package com.ruoyi.demo.controller;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.demo.util.ResultUtil;
import com.ruoyi.demo.domain.newMeet;
import com.ruoyi.demo.service.INewMeetService;
import com.ruoyi.system.mapper.MeetUserMapper;
import com.ruoyi.system.mapper.MeetMapper;
import com.ruoyi.system.domain.MeetUser;
import com.ruoyi.system.domain.Meet;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/demo/meetRequests")
public class NewMeetController {
    @Resource
    INewMeetService meetService;
    
    @Resource
    private MeetUserMapper meetUserMapper;
    
    @Resource
    private MeetMapper meetMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @PostMapping
    @Transactional
    public ResultUtil saveMeetRequests(@RequestBody newMeet meet) {
        System.out.println("接收到的数据：" +meet.getTheme());
        System.out.println("接收到的数据：" + meet.getCreatedAt());
        System.out.println("接收到的数据：" + meet);
        
        // 保存会议申请
        boolean result = meetService.add_item(meet);
        
        // 如果会议申请保存成功，则插入meet_user表数据
        if (result) {
            MeetUser meetUser = new MeetUser();
            meetUser.setMeetId(meet.getMeetId());  // 获取刚插入的会议ID
            meetUser.setUserId(meet.getUserId());  // 获取当前用户ID
            meetUser.setIsAttented("1");  // 设置默认未参会状态
            
            meetUserMapper.insertMeetUser(meetUser);
            
            // 插入会议日志数据
            Map<String, Object> logParams = new HashMap<>();

            // 获取用户名
            SysUser user = sysUserMapper.selectUserById(meet.getUserId());
            String userName = user != null ? user.getUserName() : "";
            logParams.put("meetId", meet.getMeetId());
            logParams.put("userId", meet.getUserId());
            logParams.put("attendUser", userName);
            logParams.put("operationType", "CREATE");  // 操作类型：创建会议
            logParams.put("operationResult", "SUCCESS");  // 操作结果：成功
            logParams.put("remark", "创建会议申请");  // 备注
            meetMapper.insertMeetLog(logParams);
            
            return new ResultUtil(true);
        }
        
        return new ResultUtil(false);
    }
}
